package com.sec.android.app.myfiles.listener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

import com.sec.android.app.myfiles.activity.AbsMyFilesActivity;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;

public class GmsLaunchedReceiver extends AbsBroadcastReceiverImp {

    private AbsMyFilesActivity mActivity;

    public GmsLaunchedReceiver(AbsMyFilesActivity activity, ListenerMgr.LifeCycle registerTime, ListenerMgr.LifeCycle unregisterTime) {
        super(activity, registerTime, unregisterTime);
        mActivity = activity;
    }

    @Override
    IntentFilter getIntentFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(AppConstants.MYFILES_ACTION_GMS_LAUNCHED);
        return filter;
    }

    @Override
    BroadcastReceiver getBroadcastReceiver() {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int senderProcessId = intent.getIntExtra(AppConstants.EXTRA_PROCESS_ID, -1);
                int recvProcessId = mActivity.getProcessId();
                if (senderProcessId != -1 && recvProcessId != senderProcessId) {
                    NavigationInfo info = NavigationManager.getInstance(recvProcessId).getCurInfo();
                    if (AppFeatures.isTabletUIMode() ||
                            (info != null && info.getStorageType() == FileRecord.StorageType.Home)) {
                        mActivity.invalidateOptionsMenu();
                    }
                }
            }
        };
    }

    @Override
    public void registerListener() {
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mReceiver, mIntentFilter);
    }

    @Override
    public void unregisterListener() {
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);
        mContext = null;
        mActivity = null;
    }
}
